package com.nord.Stalker;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.MapActivity;
import com.nord.R;
import com.nord.MapResources.OSMOverlay;
import com.nord.WebTools.HtmlBrowser;

public class Stalker extends MapActivity implements LocationListener {
	Button stalkerBanner;
	Typeface tf;
	String username, provider;

	// Loc = núverandi staðsetning. lm = locationmanagerinn. Locations = hnit
	// nörda frá server.
	Location loc;
	LocationManager lm;
	LocationListener listener;

	// Korta overlay-ið og korta virkni.
	OSMOverlay osmItemizedOverlay;
	private MapView mapView;
	private MapController mapController;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); 
		
		setContentView(R.layout.activity_stalker);
		stalkerBanner = (Button) findViewById(R.id.regBanner);
		tf = Typeface.createFromAsset(getAssets(), "DaysOne-Regular.ttf");
		stalkerBanner.setTypeface(tf);
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		listener = this;
		mapView = (org.osmdroid.views.MapView) findViewById(R.id.openMapviewLocation);
		mapController = mapView.getController();

		Criteria crit = new Criteria();
		crit.setAccuracy(Criteria.ACCURACY_FINE);
		provider = lm.getBestProvider(crit, false);
		lm.requestLocationUpdates(provider, 0, 0, listener);
	}

	@Override
	public void onResume() {
		super.onResume();

		isGPS();
		username = getIntent().getExtras().getString("USERNAME");
		loc = lm.getLastKnownLocation(provider);
		
		new MapLoader().execute();
	}
	
	protected void onPause() {
		super.onPause();
		lm.removeUpdates(listener);
	}

	public class MapLoader extends AsyncTask<Void, Void, String> {
		ProgressDialog progressBar;
		private boolean network, isLocation;
		String[] Locations;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(Stalker.this);
			progressBar.setCancelable(false);
			progressBar.setMessage("Er að hlaða korti..");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
			
			initMap();
			network = isNetworkAvailable();

			if(loc == null){
				Toast toast = Toast.makeText(getApplication(), "Get ekki staðsett þig!", Toast.LENGTH_SHORT);
				toast.show();
				isLocation = false;				
			}
		}

		@Override
		protected String doInBackground(Void... arg0) {
			//ef við höfum virka nettengingu þá sækjum við staðsetningar af Brainfuck.
			if(network){
				Locations = PopulateLocations();
			}
			//ef við höfum virka nettengingu og virkann 
			//staðsetningarþjón þá sendum við okkar staðsetningu á serverinn.
			if(network && isLocation && loc != null){
				sendLocation(String.valueOf(loc.getLatitude()),String.valueOf(loc.getLongitude()));
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			double lng, lat;
			populateOverlay(Locations);
			
			if(isLocation){
				lng = loc.getLongitude();
				lat = loc.getLatitude();
			}
			//ef við höfum enga staðsetningu þá fast stillum við hana á alþingi!
			else{
				lat = 64.146795;
				lng = -21.940116;
			}

			org.osmdroid.util.GeoPoint gp = new org.osmdroid.util.GeoPoint(
					(int) (lat * 1E6), (int) (lng * 1E6));
			mapController.setCenter(gp);
			osmItemizedOverlay.addItem(gp, "Point", "Point");
			progressBar.dismiss();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 0, "Center");
		menu.add(0, 2, 0, "Update");
		menu.add(0, 3, 0, "List");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// Ýtt á Center Takkann
		case 1:
			break;
		// Ýtt á Update Takkann
		case 2:
			new MapLoader().execute();
			break;
		// Ýtt á Lista Takkann.
		case 3:
			break;
		}
		return true;
	}

	private void initMap() {
		Drawable marker = getResources().getDrawable(
				android.R.drawable.star_big_on);
		int markerWidth = marker.getIntrinsicWidth();
		int markerHeight = marker.getIntrinsicHeight();
		marker.setBounds(0, markerHeight, markerWidth, 0);

		mapView.setTileSource(org.osmdroid.tileprovider.tilesource.TileSourceFactory.MAPNIK);
		mapView.setBuiltInZoomControls(true);
		mapController.setZoom(15);

		org.osmdroid.ResourceProxy resourceProxy = new org.osmdroid.DefaultResourceProxyImpl(
				getApplicationContext());
		osmItemizedOverlay = new OSMOverlay(marker, resourceProxy);
		mapView.getOverlays().add(osmItemizedOverlay);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	//Fyrir:
	//Eftir: true ef það er nettenging virk, false ef ekki.
	//notkun: boolean b = isNetworkAvailable();
	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null; 
	}
	
	//Fyrir: lm er LocationManager hlutur
	//Eftir: true ef gps er virkt, 
	//	false ef ekki og einnig verður boðið uppá að virkja GPS ef það er óvirkt.
	//notkun: boolean b = isGPS()
	private boolean isGPS() {
		boolean result = false;
		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			result = true;
		}
		else {
			result = false;
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Slökkt er á GPS-inu. Viltu kveikja á því núna?")
				.setCancelable(false).setPositiveButton("Já",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(@SuppressWarnings("unused") final DialogInterface dialog,
								@SuppressWarnings("unused") final int id) {
									startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
						}
					})
				.setNegativeButton("NEI!",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
							
						}
					});
			final AlertDialog alert = builder.create();
			alert.show();
		}
		return result;
	}
	
	//Fyrir: osmItimizedOverlay er virkt overlay fyrir open street maps kortið.
	//	Locations er fylki staðsetninga á forminu [nafn,longitude,latitude,tími]
	//Eftir: osmItimizedOverlay hefur verið fyllt með þeim hlutum sem eru í Locations fylkinu.
	//Notkun: P
	private void populateOverlay(String[] Locations) {
		for (int i = 0; i < Locations.length / 4; i++) {
		org.osmdroid.util.GeoPoint gp = new org.osmdroid.util.GeoPoint(
				(int) (Double.parseDouble(Locations[i * 4 + 1]) * 1E6),
				(int) (Double.parseDouble(Locations[i * 4 + 2]) * 1E6));
		osmItemizedOverlay.addItem(gp, Locations[i * 4],Locations[i * 4 + 3]);
		}
	}
	
	//Setur þær staðsetningar sem brainfuck gefur okkur inn í Locations listann.
	private String[] PopulateLocations() {
		String[] Locations;

		List<NameValuePair> infoGet = new ArrayList<NameValuePair>();
		infoGet.add(new BasicNameValuePair("RequestList", ""));
		String[] notJsonFood;
			notJsonFood = HtmlBrowser.postExecutor(
				"http://brainfuck.nord.is:2005/", infoGet);
			
		if (notJsonFood != null) {
			notJsonFood[0] = notJsonFood[0].replace("[", "");
			notJsonFood[0] = notJsonFood[0].replace("]", "");
			notJsonFood[0] = notJsonFood[0].replace("\"", "");

			Locations = notJsonFood[0].split(",");
		}
		else{
			Locations = new String[1];
			Locations[0] = "empty";
		}
		return Locations;
	}
	
	//sendir brainfuck okkar staðsetningu.
	private void sendLocation(String Longitude, String Latitude) {
		List<NameValuePair> infoSend = new ArrayList<NameValuePair>();
		infoSend.add(new BasicNameValuePair("PositionName", username));
		infoSend.add(new BasicNameValuePair("lat", Latitude));
		infoSend.add(new BasicNameValuePair("lon", Longitude));
		HtmlBrowser.postExecutor("http://brainfuck.nord.is:2005/", infoSend);
	}
	
	@Override
	public void onLocationChanged(Location location) {
		loc = location;
		new MapLoader().execute();
	}

	@Override
	public void onProviderDisabled(String prov) {
		Criteria crit = new Criteria();
		provider = lm.getBestProvider(crit, false);
		provider = prov;
	}

	@Override
	public void onProviderEnabled(String prov) {
		Criteria crit = new Criteria();
		provider = lm.getBestProvider(crit, false);
		provider = prov;
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}
}
